#include "MainWindow.h"
#include "ui_MainWindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    m_pImgCtrl = new FileDownLoader( this);

    connect(m_pImgCtrl, SIGNAL (downloaded()), this, SLOT (loadImage()));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_clicked()
{
    manage = new QNetworkAccessManager(this);
    QNetworkRequest network_request;
    QString cityName = "上海";

    /*设置发送数据*/
    network_request.setUrl(QUrl(QString("https://www.apiopen.top/weatherApi?city=%1")
                                .arg(cityName)));
    //network_request.setRawHeader("apikey", "您自己的apikey");

    /*建立connect，replyFinished为自定义槽函数，获取api发回来的天气信息（Jason）格式*/
    connect(manage,SIGNAL(finished(QNetworkReply *)),this,SLOT(getReplyFinished(QNetworkReply *)) );

    /*发送get网络请求*/
    manage->get(network_request);

}

void MainWindow::getReplyFinished(QNetworkReply *reply)
{
    QJsonObject data = QJsonDocument::fromJson(reply->readAll()).object();
    qDebug() << "天气Jason：" << data;
    ui->textBrowser->setText(getStringFromJsonObject(data));
}

void MainWindow::loadImage()
{
     QPixmap image;
     image.loadFromData(m_pImgCtrl->downloadedData());
     ui->buttonImage->setIcon(image);
     ui->buttonImage->setIconSize(QSize(image.width(),image.height()));
}

QJsonObject MainWindow::getJsonObjectFromByteArray(const QByteArray jsonString)
{
    QJsonDocument jsonDocument = QJsonDocument::fromJson(jsonString);
    if( jsonDocument.isNull() ){
        qDebug()<< "===> QJsonDocument："<< jsonString;
    }
    QJsonObject jsonObject = jsonDocument.object();
    return jsonObject;
}

QByteArray MainWindow::getByteArrayFromJsonObject(const QJsonObject &jsonObject)
{
    return QJsonDocument(jsonObject).toJson();

    //注意，超长数据要用到QJsonDocument::Compact参数eg:...toJson(QJsonDocument::Compact);

    //否则你会发现传过去的数据只传了一部分。
}

QJsonObject MainWindow::getJsonObjectFromString(const QString jsonString)
{
    QJsonDocument jsonDocument = QJsonDocument::fromJson(jsonString.toLocal8Bit().data());
    if( jsonDocument.isNull() ){
        qDebug()<< "===> QJsonDocument："<< jsonString.toLocal8Bit().data();
    }
    QJsonObject jsonObject = jsonDocument.object();
    return jsonObject;
}

QString MainWindow::getStringFromJsonObject(const QJsonObject &jsonObject)
{
    return QString(QJsonDocument(jsonObject).toJson());

    //注意，超长数据要用到QJsonDocument::Compact参数eg:...toJson(QJsonDocument::Compact);
    //否则你会发现传过去的数据只传了一部分。
}

void MainWindow::on_downloadImage_clicked()
{
    QUrl imageUrl("http://pics.sc.chinaz.com/Files/pic/icons128/6344/d1.png");
    m_pImgCtrl->download(imageUrl);
}
